<template>
  <div class="goTop" v-show="isShowToTop" @click="goTop">
    <i class="iconfont icon-fanhuidingbu"></i>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
let obj = null
export default {
  name: 'goTop',
  props: {
    scrollObj: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const isShowToTop = ref(false)
    const scroll = () => {
      if (obj.scrollTop >= 500 && !isShowToTop.value) {
        isShowToTop.value = true
      } else if (obj.scrollTop < 500 && isShowToTop.value) {
        isShowToTop.value = false
      }
    }
    onMounted(() => {
      nextTick(() => {
        obj = document.querySelector(props.scrollObj)
        obj.addEventListener('scroll', scroll, false)
      })
    })
    onUnmounted(() => {
      console.log('onUnmounted')
      obj.removeEventListener('scroll', scroll, false)
    })
    const goTop = () => {
      obj.scrollTo({
        behavior: 'smooth',
        top: 0
      })
    }
    return {
      goTop,
      isShowToTop
    }
  }
}
</script>

<style scoped>
.goTop {
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  bottom: 80px;
  right: 50px;
  height: 35px;
  width: 35px;
  border-radius: 50%;
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.1);
  background: #fafafa;
  z-index: 200;
  cursor: pointer;
}
</style>